package com.kehutong.admin.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.coraframework.util.Objects;

import com.kehutong.admin.entity.TreeResource;
import com.kehutong.common.entity.Root;

public class TreeEntityUtil {
	

    /**
     * 将TreeEntity按ID转为Map
     * @param list
     * @return
     */
    public static <T extends TreeResource<T>> Map<String, T> asMapById(List<T> list) {
        Map<String, T> map = new LinkedHashMap<>();
        
        if (Objects.nonEmpty(list)) {
            for (T treeEntity : list) {
                map.put(treeEntity.getId(), treeEntity);
            }
        }
        
        return map;
    }
    
    public static List<String> merge(List<String> strList1, List<String> strList2) {
    	List<String> strList = new ArrayList<>();
    	
    	if (Objects.nonEmpty(strList1)) {
    		strList.addAll(strList1);
    	}
    	
    	if (Objects.nonEmpty(strList2)) {
    		strList.addAll(strList2);
    	}
    	
    	return strList;
    }
    
    /**
     * <pre>将菜单列表组织为菜单树</pre>
     *
     * @param topElement
     * @param list
     * @return
     */
    public static <T extends TreeResource<T>> T  organizeAsTree(List<T> list) {
    	Map<String, T> items = asMapById(list);

    	for (T item : list) {
    		if (Objects.nonEmpty(item.getParent_id())) {
    			T parent = items.get(item.getParent_id());
    			if (Objects.nonNull(parent)) {
    				parent.addChild(item);
    			}
    		}
    	}

    	return items.get(Root.ROOT_ID);
    }

	/**
	 * <pre>将菜单列表组织为菜单树</pre>
	 *
	 * @param id
	 * @param list
	 * @return
	 */
	public static <T extends TreeResource<T>> T  organizeAsTree(List<T> list, String id) {
		Map<String, T> items = asMapById(list);

		for (T item : list) {
			if (Objects.nonEmpty(item.getParent_id())) {
				T parent = items.get(item.getParent_id());
				if (Objects.nonNull(parent)) {
					parent.addChild(item);
				}
			}
		}

		return items.get(id);
	}
    
    /**
     * <pre>将菜单列表组织为菜单树</pre>
     *
     * @param topElement
     * @param list
     * @return
     */
    public static <T extends TreeResource<T>> T organizeAsTree(Map<String, T> items, boolean sortAble) {
    	List<T> itemList = new ArrayList<>(items.size());
    	items.forEach((k, v)->itemList.add(v));
    	
    	if (sortAble) {
    		Collections.sort(itemList);
    	}
    	
    	for (T item : itemList) {
    		if (Objects.nonEmpty(item.getParent_id())) {
    			T parent = items.get(item.getParent_id());
    			if (Objects.nonNull(parent)) {
    				parent.addChild(item);
    			}
    		}
    	}

    	return items.get(Root.ROOT_ID);
    }
}
